package logic

import (
	"context"
	"platform/internal/svc"
	"platform/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (*types.LoginResp, error) {
	// 验证用户名密码
	user, err := l.authenticate(req.Username, req.Password)
	if err != nil {
		l.Logger.Errorf("用户 %s 登录失败: %v", req.Username, err)
		return nil, types.ErrAuthFailed
	}

	// 生成Token
	token, expiresAt, err := l.svcCtx.Auth.GenerateToken(user.ID, user.Username)
	if err != nil {
		l.Logger.Errorf("生成Token失败: %v", err)
		return nil, types.ErrGenerateToken
	}

	l.Logger.Infof("用户 %s 登录成功", req.Username)

	return &types.LoginResp{
		Success:   true,
		Token:     token,
		ExpiresAt: expiresAt,
		User: types.UserInfo{
			ID:       user.ID,
			Username: user.Username,
			Role:     user.Role,
		},
	}, nil
}

func (l *LoginLogic) authenticate(username, password string) (*types.User, error) {
	// 这里应该是从数据库验证用户
	// 为了演示，使用硬编码的用户
	if username == "admin" && password == "admin123" {
		return &types.User{
			ID:       "1",
			Username: "admin",
			Role:     "system_admin",
		}, nil
	}

	if username == "user" && password == "user123" {
		return &types.User{
			ID:       "2",
			Username: "user",
			Role:     "normal_user",
		}, nil
	}

	return nil, types.ErrAuthFailed
}
